package com.zzy.netty.learn.demo.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * 
 * Title: HelloServerInitializer Description: Netty 服务端过滤器 Version:1.0.0
 * 
 * @author guokaige
 * @date 2017-8-31
 */
public class NettyServerFilter extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		
		// 负责通过4字节Header指定的Body长度将消息切割
		pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
		// 负责将写入的字节码加上4字节Header前缀来指定Body长度
		pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
		// 解码和编码，应和客户端一致
		pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
		pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

		pipeline.addLast("handler", new NettyServerHandler());// 服务端业务逻辑
	}
}